<template>
	<view v-if="imgUrl" class="upload" :style="{width: $xl.parseUnit(width, 'rpx'), height: $xl.parseUnit(height, 'rpx')}">
		<image class="upload-img" :src="imgUrl" @click="editImg"></image>
		<view v-if="closeable" class="upload-close" @click="deleteImage">
			<xl-icon name="xl-close" :size="10" color="#fff"></xl-icon>
		</view>
		<view v-if="editEnable" class="edit" @click="editImg">编辑</view>
	</view>
	<view v-else class="upload" @click="chooseImage" :style="{width: $xl.parseUnit(width, 'rpx'), height: $xl.parseUnit(height, 'rpx')}">
		<xl-icon name="xl-camera" :size="iconSize" bottom="6rpx" color="#b1b1b1"></xl-icon>
		<view class="text">{{tip}}</view>
	</view>
	<xl-image-cropper v-if="editImgUrl" mode="ratio" :width="width" :height="height" :url="editImgUrl" @cancel="cancelEdit" @ok="okEdit"></xl-image-cropper>
</template>

<script setup>
	import { computed, watch, ref } from "vue";
	import propsData from './props.js'
	const props = defineProps(propsData)
	
	const imgUrl = ref('')
	
	const emits = defineEmits(['update:modelValue'])
	
	watch(() => props.url, newVal => {
		if(newVal)  imgUrl.value = newVal
	}, {immediate: true})
	
	function chooseImage() {
		uni.chooseImage({
			count: 1,
			success: res => {
				imgUrl.value = res.tempFilePaths[0]
				if(props.editEnable) editImgUrl.value = imgUrl.value
			}
		})
	}
	
	function deleteImage() {
		imgUrl.value = ''
	}
	
	let editImgUrl = ref('')
	function editImg(){
		if(props.editEnable){
			editImgUrl.value = imgUrl.value
		}
	}
	function okEdit(e) {
		editImgUrl.value = "";
		imgUrl.value = e.path;
	}
	function cancelEdit() {
		// url设置为空，隐藏控件
		editImgUrl.value = "";
	}
	
	async function upload() {
		if(imgUrl.value && !imgUrl.value.startsWith('http')) {
			let img = await uni.$xl.upload.uploadFile(imgUrl.value, props.uploadPath)
			return img 
		} else if(imgUrl.value && imgUrl.value.startsWith('http')) {
			return imgUrl.value
		} else {
			return ''
		}
	}
	
	defineExpose({upload})
</script>

<style lang="scss" scoped>
	.upload {
		background-color: #f9f9f9;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		border-radius: 12rpx;
		position: relative;
		overflow: hidden;
		.text {
			font-size: 24rpx;
			color: #b1b1b1;
			margin-top: 10rpx;
		}
	}
	.upload-img {
		width: 100%;
		height: 100%;
	}
	.upload-close {
		position: absolute;
		top: 0;
		right: 0;
		background-color: #e54d42;
		width: 36rpx;
		height: 36rpx;
		border-bottom-left-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.edit {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 70rpx;
		height: 40rpx;
		background-color: rgba(0, 0, 0, 0.3);
		border-top-right-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 22rpx;
		color: #ffffff;
	}
</style>